<?php

namespace App\Controllers;

class upload extends BaseController
{
    public function upload($file,$path){
        $filename = $file->getRandomName();
        if($file->isValid()&& !$file->hasMoved()){
            $file->move($path,$filename);
            return base_url($path.$filename);
        }else{
            return false;
        }
    }

    public function article_img(){
        $data["u_id"] = '';
        $data['path'] = '';
        if(!$this -> is_login()) {
            return print_r($this->json_result(false, '请登录账号', $data));
        }
        $file = $this->request->getFile("article_img");
        $u_id = $this->session->get('u_id');
        $data["u_id"] = $u_id;
        if(!$file) {
            return print_r($this->json_result(false, '图片不存在', $data));
        }

        $path = $this->upload($file,$this->article_path);
        if(!$path) {
            return print_r ($this->json_result(false, '上传失败', $data));
        }
        $data['path'] = $path;
        print_r ($this->json_result(true, '上传成功', $data));
    }

    public function avatar(){
        $data["u_id"] = '';
        if(!$this -> is_login()) {

            return print_r($this->json_result(false, '请登录账号', $data));
        }
        $u_id = $this->session->get('u_id');
        $data["u_id"] = $u_id;
        $file = $this->request->getFile("avatar");
        if(!$file) {
            return print_r($this->json_result(false, '图片不存在', $data));
        }

        $path = $this->upload($file,$this->avatar_path);
        if(!$path) {
            return print_r($this->json_result(false, '上传失败', $data));
        }
        $data['path'] = $path;
        if(!$this->user_model -> update_data($u_id,["avatar"=>base_url($path)])) {
            return print_r ($this->json_result(false, '存入数据库失败', $data));
        }
        print_r ($this->json_result(true, '上传成功', $data));
    }

    public function valid_qualification(){
        $this->validation->setRule('valid_qualification', '专业','is_image');

        $data["u_id"] = '';
        if(!$this -> is_login()) {
            return print_r($this->json_result(false, '请登录账号', $data));
        }
        $u_id = $this->session->get('u_id');
        $data["u_id"] = $u_id;
        $file = $this->request->getFile("valid_qualification");
        if(!$file) {
           return print_r($this->json_result(false, '图片不存在', $data));
        }

        $path = $this->upload($file,$this->qualification_path);
        if(!$path) {
            return print_r($this->json_result(false, '上传失败', $data));
        }
        $data['path'] = $path;
        if(!$this->user_model -> update_data($u_id,["valid_qualification"=>base_url($path)])) {
            return print_r ($this->json_result(false, '存入数据库失败', $data));
        }
        print_r ($this->json_result(true, '上传成功', $data));
    }
}